﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Wicresoft.Logger;
using Wicresoft.WebHost;

namespace Wicresoft.Task.Common
{
    public class ARSysWeb : HostTask
    {
        private IWebHost host;
        private int port;

        public override void OnStart()
        {
            if (host == null)
            {
                port = int.Parse(Bag.Port);
                host = AspHost.Create(port, "/", Directory.GetCurrentDirectory());
            }
            if (host != null)
            {
                int tryTime = 5;
                int sleepInterval = 2500;

                while (tryTime-- > 0)
                {
                    try
                    {
                        host.Start();
                        break;
                    }
                    catch (System.Net.HttpListenerException e)
                    {
                        if (e.ErrorCode == 183 && tryTime > 0)
                        {
                            Log.Debug(Name, "{0}, sleep {1} seconds", e.ErrorCode, sleepInterval / 1000.0);
                            System.Threading.Thread.Sleep(sleepInterval);
                        }
                        else
                        {
                            Log.Error(Name, "Failed to start asp, {0}", e.ErrorCode);
                            throw;
                        }
                    }
                }

                Log.Info("Asp", "Host ARSysWeb [:{0}] has started.", port);
            }
        }

        public override void OnStop()
        {
            if (host != null)
            {
                host.Stop();
                Log.Info("Asp", "Host ARSysWeb has stopped.");
            }
        }
    }
}
